package com.example.filters;

import com.alibaba.fastjson.JSON;
import com.example.common.entitys.AuthUserDetails;
import com.example.threadloacls.AuthUserDetailsThreadlocal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(UserInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("执行UserInterceptor");


        AuthUserDetails userDto =  null;
        String url = request.getRequestURI();

        String  currentuser = request.getHeader("currentuser");
        String  token = request.getHeader(HttpHeaders.AUTHORIZATION);
        logger.info("访问资源，url="+url+",currentuser="+currentuser+",token="+token);
        MDC.put("currentuser",currentuser);
        MDC.put("token",token);
        if(StringUtils.hasLength(currentuser)){
            userDto = JSON.parseObject(currentuser,AuthUserDetails.class);
        }
        if(userDto == null){
            AuthUserDetailsThreadlocal.setUserSession(null);
        }else{
            AuthUserDetailsThreadlocal.setUserSession(userDto);

        }

         return true;



    }
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        if(AuthUserDetailsThreadlocal.getUserSession() != null){
            AuthUserDetailsThreadlocal.removeUser();
        }else{
            AuthUserDetailsThreadlocal.removeUser();
        }

        MDC.remove("currentuser");
        MDC.remove("token");
    }
}
